package com.mayikt.controller;

import com.mayikt.loadbalance.LoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @program: mayikt-springcloud-alibaba
 * @description
 * @author: tianya
 * @create: 2020-05-21 20:22
 **/
@RestController
public class OrderController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancer loadBalancer;

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    @GetMapping("/orderToMember")
    public String orderToMember(){
        //根据服务名称从 注册中心获取集群列表地址
        List<ServiceInstance> instances = discoveryClient.getInstances("meite-member");

        ServiceInstance singleAddress = loadBalancer.getSingleAddress(instances);
//        ServiceInstance serviceInstance = instances.get(0);
//        URI rpcMemberUrl = serviceInstance.getUri();
        String result = restTemplate.getForObject(singleAddress.getUri() + "/getUser", String.class);
        //列表任意选择一个， 实现本地rpc调用 rest模板
        return result;
    }

    @GetMapping("/orderToRibbon")
    public String orderToRibbon(){
        //根据服务名称从 注册中心获取集群列表地址
        String result = restTemplate.getForObject("http://meite-member/getUser", String.class);
        //列表任意选择一个， 实现本地rpc调用 rest模板
        return result;
    }

    @GetMapping("/loadBalancerMember")
    public Object loadBalancerClientMember(){
        ServiceInstance instance = loadBalancerClient.choose("meite-member");
        return instance;
    }
}
